import psycopg2
from pprint import pprint
import ConfigParser
conn = None
try:
	config = ConfigParser.RawConfigParser()
	config.read('/etc/ude/switch/database.ini')
	conn = psycopg2.connect("dbname='{0}' user='{1}' host='{2}' password='{3}'".format(config.get('Database','dbname'),config.get('Database','user'),config.get('Database','host'),config.get('Database','password')));
except:
	print "I am unable to connect to the database"

remote_sip_rows = None
internal_sip_rows = None

if __name__ == "__main__":
	
	c = conn.cursor()
	c.execute("""SELECT name,host,port,username,secret FROM t_outbound_sip;""")
	remote_sip_rows = c.fetchall()
	del c
	
	# External SIP registration.
	print "[general]"
	print "disallow=all"
	print "allow=ulaw"
	print "language=en"
	print ""
	for row in remote_sip_rows:
		print "register => {0}:{1}@{2}:{3}".format(row[3],row[4],row[1],row[2])
	print ""
	
	# Local SIP hardware.
	c = conn.cursor()
	c.execute("""SELECT did,cid,ata,line,mailbox,secret FROM v_sip_int_users;""")
	internal_sip_rows =  c.fetchall()
	del c
	
	for row in internal_sip_rows:
		print "[ATA-{0}-L{1}]".format(row[2],row[3])
		print "type=friend"
		print "context={0}_phone".format(row[0])
		print "accountcode={0}".format(row[0])
		print "host=dynamic"
		print "secret={0}".format(row[5])
		print 'callerid="{0}" <{1}>'.format(row[1],row[0])
		if row[4] != None:
			print "mailbox={0}@default".format(row[4])
		print ""
	
	for row in remote_sip_rows:
		print "[{0}]".format(row[0])
		print "context=inbound"
		print "type=friend"
		print "host={0}".format(row[1])
		print "username={0}".format(row[3])
		print "accountcode={0}".format(row[3])
		print "secret={0}".format(row[4])
		print "canreinvite=no ; if using a nat, do not change"
		print "insecure=port,invite ; do NOT remove this"
		print "qualify=5000 ; do NOT remove this"
		print "dtmfmode=auto"
		print "nat=no ; do NOT remove/change this"
		print "disallow=all"
		print "allow=ulaw"
		print ""





























